/** 工具包 */
import request from './Request';
import toast from './Toast';
/** 应用接口 */
import {
  UserOperationDetail,
  LoginForm,
  RegisterForm,
  UserMsg,
  UserMsgUpdateInfo,
  UserMsgUpdateResponse, UserFocusOrFansPaging, UserCentre7DaysStatics, UserFocusAndFansPaging
} from '@/interface/user/entity/UserEntityInterface';
import {
  FileResponseEntity,
  FileDownloadResponseEntity,
  FileDataResponseEntity
} from '@/interface/file/entity/FileEntittyInterface';
import {
  DetailPageInfo,
  DetailResponseData,
  DetailPublish,
  DetailInfo
} from '@/interface/detail/entity/DetailEntityInterface';
import {ShareLinkEntity, ShareLinkResponse} from '@/interface/link/share/entity/ShareLinkEntity';
import {FeedbackResponseEntity, FeedbackCommitEntity} from "@/interface/feedback/entity/FeedbackEntityInterface";
import {FriendlyLinkEntity} from '@/interface/link/friendly/entity/FriendlyLinkEntity';
import {QuestionResponse, QuestionInfo, QuestionPaging} from '@/interface/question/entity/QuestionEntity';
import {AnswerResponse, AnswerReply, ReplyMode} from '@/interface/answer/entity/AnswerEntity';
import {
  DetailComments,
  Comment,
  DetailCommentInfo,
  KudosComment
} from '@/interface/comment/entity/CommentEntityInterface';

const isHttps = 'https:' == document.location.protocol, isProd = process.env.NODE_ENV === 'production';
let requestUrl;
// 生产环境要判断是否为 https
if (isProd) {
  if (isHttps) {
    requestUrl = 'http://yeziji.xyz/file';
  } else {
    requestUrl = 'https://yeziji.xyz/file';
  }
} else {
  requestUrl = 'http://127.0.0.1:9999/file';
}

export const CUSTOMER_FILE = requestUrl;


/** 论坛请求和文件库请求前缀 */
const FORUM_PREFIX = '/forum', FILE_PREFIX = '/file';
/** 用户文章接口 */
const USER_DETAIL = FORUM_PREFIX + '/details/allList',
  /** 单篇文章 */
  SINGLE_DETAIL = FORUM_PREFIX + '/details/get',
  /** 用户操作文章 */
  USER_OPERATION_DETAIL = FORUM_PREFIX + '/userDetail/update',
  /** 用户删除文章 */
  USER_DELETE_DETAIL = FORUM_PREFIX + '/details/delete',
  /** 用户回复文章 */
  USER_RECOVERY_DETAIL = FORUM_PREFIX + '/details/recovery';
/** 文章接口 */
const INDEX_DETAIL = FORUM_PREFIX + '/details/list',
  /** 发布文章 */
  PUBLISH_DETAIL = FORUM_PREFIX + '/details/save';
/**
 * 获取文章评论
 */
const DETAIL_COMMENTS = FORUM_PREFIX + '/comment/detail',
  /** 发起评论 */
  REPLY_COMMENT = FORUM_PREFIX + '/comment/reply';
/** 用户操作评论 */
const KUDOS_COMMENT = FORUM_PREFIX + '/userComment/good';
/** 用户登录 */
const USER_LOGIN = FORUM_PREFIX + '/login',
  /** 注册用户 */
  USER_REGISTER = FORUM_PREFIX + '/user/register',
  /** 更新用户信息 */
  USER_UPDATE = FORUM_PREFIX + '/user/update',
  /** 获取用户总数 */
  USER_COUNT = FORUM_PREFIX + '/user/count',
  /** 根据用户昵称获取用户信息 */
  USER_MSG = FORUM_PREFIX + '/user/msg',
  /**
   * 批量获取用户信息
   */
  USER_MSG_LIST = FORUM_PREFIX + '/user/msgs',
  /** 获取用户的粉丝列表或关注列表 */
  FOCUS_OR_FANS = FORUM_PREFIX + '/user/focusOrFans',
  /** 获取用户的粉丝和关注列表 */
  FOCUS_AND_FANS = FORUM_PREFIX + '/user/focusAndFans';
/** 专栏 */
const SPECIAL_LIST = FORUM_PREFIX + '/special/list';
/** 标签 */
const TAGS_LIST = FORUM_PREFIX + '/tags/list';
/** 邮箱 */
const EMAIL_SEND_CODE = FORUM_PREFIX + '/user/code';
/** markdown */
const MD_FILE_UPLOAD = FORUM_PREFIX + '/markdown/read';
/** 获取文件列表 */
const GET_FILE_LIST = FILE_PREFIX + '/list',
  /** 下载文件 */
  GET_DOWNLOAD_FILE = FILE_PREFIX + '/get',
  /** 上传文件进度 */
  GET_FILE_PROCESS = FILE_PREFIX + '/process',
  /** 获取文件数据列表 */
  GET_DATA_FILE_LIST = FILE_PREFIX + '/docs',
  /** 聊天室上传图片 */
  CHAT_UPLOAD_IMAGE = FILE_PREFIX + '/directCloud';
/** 提交反馈 */
const COMMIT_FEEDBACK = FORUM_PREFIX + '/feedback/commit',
  /** 反馈信息列表 */
  FEEDBACK_LIST = FORUM_PREFIX + '/feedback/list';
/** 分享链接 */
const SHARE_LINK = FORUM_PREFIX + '/share/submit',
  /**分享链接列表 */
  SHARE_LINK_LIST = FORUM_PREFIX + '/share/list';
/** 友情链接 */
const FRIENDLY_LIST = FORUM_PREFIX + '/friendly/list';
/** 提问分页列表 */
const QUESTION_LIST = FORUM_PREFIX + '/question/list',
  /** 提交提问 */
  SUBMIT_QUESTION = FORUM_PREFIX + '/question/submit',
  /** 获取当前提问 */
  GET_QUESTION = FORUM_PREFIX + '/question/get';
/**
 * 回答列表
 */
const ANSWER_LIST = FORUM_PREFIX + '/answer/list',
  /** 回复问题 */
  ANSWER_REPLY = FORUM_PREFIX + '/answer/reply';
/**
 * 操作问题或答案
 */
const QA_ACTION = FORUM_PREFIX + '/qa/action';

/** 个人中心 -- 获取 4 个关注用户 */
const USER_CENTRE_FOCUS = FORUM_PREFIX + '/centre/focusOrFans',
  /** 个人中心 -- 统计文章数据 */
  STATICS_DETAIL_CHART = FORUM_PREFIX + '/centre/statics',
  /** 个人中心 -- 获取文章 */
  GET_USER_DETAILS = FORUM_PREFIX + '/centre/dlist',
  /** 根据用户昵称获取专栏列表 */
  GET_SPECIAL_LIST_BY_NICKNAME = FORUM_PREFIX + '/centre/special',
  /** 根据昵称获取标签 */
  GET_TAGS_BY_NICKNAME = FORUM_PREFIX + '/centre/tags';

/** 聊天室 */
const USER_CHATROOM_CONTACT = FORUM_PREFIX + '/chatroom/private';

function parseFormData(data) {
  let fd = new FormData()
  if (data && data instanceof Object) {
    for (let key in data) {
      fd.append(key, data[key]);
    }
  }
  return fd;
}

/** 统一响应体 */
export interface ResponseResult<T> {
  /** 响应码 */
  code: number,
  /** 响应数据 */
  data: T,
  /** 响应消息提示 */
  msg: string
}

/** 统一分页响应数据 */
export interface PaginatorResponseResult<T> {
  /** 数据数量 */
  count: number,
  /** 数据数组 */
  data: T[],
  /** 分页的范围 */
  limit: number,
  /** 页码 */
  page: number,
  /** 总数据 */
  total: number,
  /** 总页数 */
  totalPage: number
}

/** 简单分页信息 */
export interface EasyPageInfo {
  size: number,
  limit: number
}

export interface Paging {
  page: number
  limit: number
}

/** 简单分页信息2 */


/** 文章服务 */
export class DetailService {
  /**
   * 根据id获取文章
   */
  async getDetailById(detailInfo: { id: number, tempSave: boolean }) {
    return await request.get(SINGLE_DETAIL, detailInfo) as ResponseResult<DetailResponseData>;
  }

  /**
   * 获取用户文章
   * @param pageInfo 分页请求体
   */
  async getUserDetails(pageInfo: DetailPageInfo) {
    return await request.get(USER_DETAIL, pageInfo) as ResponseResult<DetailResponseData[]>;
  }

  /**
   * 获取首页文章
   * @param pageInfo 分页请求体
   */
  async getIndexDetails(pageInfo: DetailPageInfo) {
    return await request.get(INDEX_DETAIL, pageInfo) as ResponseResult<PaginatorResponseResult<DetailResponseData>>;
  }

  /**
   * 用户操作文章[点赞\收藏\评分]
   * @param opera 操作信息
   */
  async operationDetails(opera: UserOperationDetail) {
    return await request.post(USER_OPERATION_DETAIL, opera) as ResponseResult<string>;
  }

  /**
   * 保存文章
   * <p>保存或暂存会返回 id 用于更新文章内容</p>
   * @param entity 保存文章的内容
   */
  async publishDetail(entity: DetailPublish) {
    let result = await request.post(PUBLISH_DETAIL, entity) as ResponseResult<number>;
    if (result.code === 0) {
      toast.success('操作成功', result.msg, 3000);
    }
    return result;
  }

  /**
   * 删除文章
   */
  async deleteDetail(info: { id: number }) {
    let result = await request.post(USER_DELETE_DETAIL, {id: info.id}) as ResponseResult<number>;
    if (result.code === 0) {
      toast.success('操作成功', result.msg, 3000);
    }
    return result;
  }

  /**
   * 恢复文章
   */
  async recoveryDetail(info: { id: number }) {
    let result = await request.post(USER_RECOVERY_DETAIL, {id: info.id}) as ResponseResult<number>;
    if (result.code === 0) {
      toast.success('操作成功', result.msg, 3000);
    }
    return result;
  }

  /**
   * 个人中心分页数据
   *
   * @param paging nickname 是必要参数
   * */
  async getCentreDetail(paging: DetailPageInfo) {
    return await request.get(GET_USER_DETAILS, paging) as ResponseResult<PaginatorResponseResult<DetailResponseData>>;
  }


}

/** 用户服务 */
export class UserService {
  /**
   * 用户登录
   * @param loginForm {username: 账号, password: 密码}
   */
  async login(loginForm: LoginForm) {
    let res = await request.post(USER_LOGIN, loginForm) as ResponseResult<UserMsg>;
    if (res.code === 0) {
      toast.success('登录成功', `欢迎您回来${res.data.nickname}`, 3000);
      return res.data;
    }
  }

  /**
   * 注册用户
   * @param registerForm 注册用户表单
   */
  async register(registerForm: RegisterForm) {
    let res = await request.post(USER_REGISTER, registerForm) as ResponseResult<any>;
    if (res.code === 0) {
      toast.success('恭喜你', '注册成功，请保存自己的账号与密码哦~', 3000);
    }
  }

  /**
   * 发送邮箱验证码
   * @param email 电子邮箱地址
   * @param timestamp 加密时间戳
   */
  async sendEmailCode(email: string, timestamp: string) {
    const form = new FormData();
    form.set('to', email);
    form.set('timestamp', timestamp);
    return await request.post(EMAIL_SEND_CODE, form)
  }

  /**
   * 更新用户信息
   * @param updateInfo 更新信息
   */
  async update(updateInfo: UserMsgUpdateInfo) {
    return await request.post(USER_UPDATE, parseFormData(updateInfo)) as ResponseResult<UserMsgUpdateResponse>;
  }

  /**
   * 获取用户总数
   */
  async getUserCount() {
    let res = await request.get(USER_COUNT) as ResponseResult<number>;
    if (res.code === 0) {
      return res;
    }
  }

  /**
   * 获取用户信息
   * @param nickname 用户昵称
   */
  async getUserMsg(nickname?: string) {
    if (nickname !== undefined) {
      return await request.post(USER_MSG, parseFormData({nickname: nickname})) as ResponseResult<UserMsg>;
    } else {
      return await request.post(USER_MSG) as ResponseResult<UserMsg>;
    }
  }

  /**
   * 批量获取用户信息
   * @param nickname 批量获取的用户
   */
  async getUserMsgList(nickname: string[]) {
    return await request.post(USER_MSG_LIST, nickname) as ResponseResult<UserMsg[]>;
  }

  /**
   * 分页获取用户的关注列表或粉丝列表
   *
   * @param paging 分页对象
   */
  async getUserFocusOrFansByPaging(paging: UserFocusOrFansPaging) {
    return await request.post(FOCUS_OR_FANS, paging) as ResponseResult<PaginatorResponseResult<UserMsg>>;
  }

  async getUserFocusAndFansByPaging(paging: UserFocusAndFansPaging) {
    return await request.post(FOCUS_AND_FANS, paging) as ResponseResult<PaginatorResponseResult<UserMsg>>;
  }

  /**
   * 根据 nickname 获取个人中心的关注列表渲染数据【nickname 为 null 时获取自身】
   * @param nickname 用户昵称
   */
  async getUserCentreFocusList(nickname?: string) {
    return await request.post(USER_CENTRE_FOCUS, {nickname}) as ResponseResult<UserMsg[]>;
  }

  /**
   * 个人中心图标统计服务
   * @param nickname 用户昵称
   */
  async centreDetailStatics(nickname?: string) {
    if (nickname && nickname.trim() !== '') {
      return await request.post(STATICS_DETAIL_CHART, parseFormData({nickname: nickname})) as ResponseResult<UserCentre7DaysStatics>;
    }
    return await request.post(STATICS_DETAIL_CHART) as ResponseResult<UserCentre7DaysStatics>;
  }

}

/** 响应数据 */
export interface SpecialResult {
  name: string,
  username: string,
  createTime: string
}

/** 专栏服务 */
export class SpecialService {
  /** 获取专栏列表 */
  async getSpecialList() {
    let res = await request.get(SPECIAL_LIST) as ResponseResult<SpecialResult[]>;
    if (res.code === 0) {
      return res;
    }
  }

  /** 根据用户昵称获取专栏 */
  async getSpecialListByNickname(nickname: { nickname: string }) {
    return await request.post(GET_SPECIAL_LIST_BY_NICKNAME, parseFormData(nickname)) as ResponseResult<SpecialResult[]>;
  }
}

/** 标签服务 */
export class TagService {
  /** 分页获取 tag */
  async getTagList(page: EasyPageInfo) {
    let res = await request.post(TAGS_LIST, page) as ResponseResult<string[]>;
    if (res.code === 0) {
      return res;
    }
  }

  /** 获取全部 tag */
  async getAllTags() {
    let res = await request.post(TAGS_LIST, {all: true}) as ResponseResult<string[]>;
    if (res.code === 0) {
      return res;
    }
  }

  /**
   * 根据昵称获取标签
   * @param nickname 昵称
   */
  async getTagsByNickname(nickname: { nickname: string }) {
    return await request.post(GET_TAGS_BY_NICKNAME, parseFormData(nickname)) as ResponseResult<string[]>;
  }
}

/** markdown 服务 */
export class MarkdownService {
  /** 上传图片 */
  async uploadFile(file) {
    let form = new FormData();
    form.append('file', file);
    let res = await request.post(MD_FILE_UPLOAD, form);
    if (res.code === 0) {
      return res.data;
    }
  }
}

/** 文件服务 */
export class FileService {
  /** 文件列表 */
  async list() {
    let form = new FormData();
    form.append('rootPath', 'common');
    let res = await request.post(GET_FILE_LIST, form) as ResponseResult<FileResponseEntity[]>;
    if (res.code === 0) {
      return res.data;
    }
  }

  /** 文件下载 */
  async download(filename: string) {
    let res = await request.post(GET_DOWNLOAD_FILE, parseFormData({
      filename,
      rootPath: 'common'
    })) as ResponseResult<FileDownloadResponseEntity>;
    if (res.code === 0) {
      return res.data;
    }
  }

  /** 获取文件进度 */
  async getProcess(md5: string) {
    let res = await request.post(GET_FILE_PROCESS, parseFormData({md5: md5}));
    if (res.code === 0) {
      return res.data;
    }
  }

  /**
   * 获取 docs
   * @param paging 分页信息
   */
  async docs(paging: Paging) {
    let res = await request.get(GET_DATA_FILE_LIST, paging) as ResponseResult<PaginatorResponseResult<FileDataResponseEntity>>;
    if (res.code == 0) {
      return res.data;
    }
  }

  /** 上传聊天图片
   * @param data 图片表单 files[]
   * */
  async uploadChatImage(data: FormData) {
    data.append('path', 'chat');
    let res = await request.post(CHAT_UPLOAD_IMAGE, data) as ResponseResult<string[]>;
    if (res.code === 0) {
      return res.data;
    }
  }
}

/** 反馈服务 */
export class FeedbackService {
  /** 提交反馈 */
  async commit(info: FeedbackCommitEntity) {
    let res = await request.post(COMMIT_FEEDBACK, info) as ResponseResult<string>;
    if (res.code === 0) {
      return res;
    }
  }

  /** 反馈列表 */
  async list(paging: Paging) {
    let res = await request.get(FEEDBACK_LIST, paging) as ResponseResult<PaginatorResponseResult<FeedbackResponseEntity>>;
    if (res.code === 0) {
      return res.data;
    }
  }
}

/** 分享链接服务 */
export class ShareLinkService {
  /** 提交审核 */
  async submit(entity: ShareLinkEntity) {
    let res = await request.post(SHARE_LINK, entity) as ResponseResult<number>;
    if (res.code === 0) {
      return res;
    }
  }

  /** 分页链接 */
  async list(page: Paging) {
    let res = await request.get(SHARE_LINK_LIST, page) as ResponseResult<PaginatorResponseResult<ShareLinkResponse>>;
    if (res.code === 0) {
      return res;
    }
  }
}

/** 友情链接服务 */
export class FriendlyService {
  /** 友情链接列表 */
  async list() {
    let res = await request.get(FRIENDLY_LIST) as ResponseResult<FriendlyLinkEntity[]>;
    if (res.code === 0) {
      return res;
    }
  }
}

/** 提问服务 */
export class QuestionService {
  /**
   * 提问的分页列表
   * @param paging 分页数据
   */
  async list(paging: QuestionPaging) {
    let res = await request.get(QUESTION_LIST, paging) as ResponseResult<PaginatorResponseResult<QuestionResponse>>;
    if (res && res.code === 0) {
      return res;
    }
  }

  /**
   * 提交提问
   * @param info 问题的信息
   */
  async submit(info: QuestionInfo) {
    let res = await request.post(SUBMIT_QUESTION, info) as ResponseResult<any>;
    if (res.code === 0) {
      return res;
    }
  }

  /**
   * 获取单个question
   * @param id question ID
   */
  async get(id: string) {
    let res = await request.restful(GET_QUESTION, [id]) as ResponseResult<QuestionResponse>;
    if (res.code === 0) {
      return res;
    }
  }

  /**
   * 收藏问题
   * @param id 问题 id
   */
  async collection(id: number) {
    let res = await request.post(QA_ACTION, {mode: 0, id: id}) as ResponseResult<boolean>
    if (res.code === 0) {
      return res;
    }
  }
}

/**
 * 答案服务
 */
export class AnswerService {
  /**
   * 获取问题下的全部回答 -- 包括回复
   * @param questionId 问题id
   */
  async list(questionId: string) {
    let res = await request.restful(ANSWER_LIST, [questionId]) as ResponseResult<AnswerResponse[]>;
    if (res.code === 0) {
      return res;
    }
  }

  /**
   * 回复指定内容
   * @param reply 回复的内容
   */
  async reply(reply: AnswerReply) {
    let res = await request.post(ANSWER_REPLY, reply) as ResponseResult<any>;
    if (res.code === 0) {
      return res;
    }
  }

  /**
   * 点赞答案
   * @param id 答案 id
   */
  async kudos(id: number) {
    let res = await request.post(QA_ACTION, {id: id, mode: 1}) as ResponseResult<any>;
    if (res.code === 0) {
      return res;
    }
  }
}

/**
 * 评论服务
 */
export class CommentService {
  /**
   * 文章评论列表
   * @param id 文章的id
   */
  async detailComments(id: number) {
    let res = await request.restful(DETAIL_COMMENTS, [id]) as ResponseResult<DetailComments[]>;
    if (res.code === 0) {
      return res;
    }
  }

  /**
   * 发送评论
   */
  async relyComment(info: DetailCommentInfo) {
    return await request.post(REPLY_COMMENT, info) as ResponseResult<number>;
  }

  /**
   * 点赞评论
   */
  async kudosComment(info: KudosComment) {
    return await request.post(KUDOS_COMMENT, info) as ResponseResult<number>;
  }
}

export class ChatroomService {
  /**
   *  获取可以联系的用户
   *  @param paging 因为这里主要数据是粉丝和关注对象，因此直接利用即可
   * */
  async getUserContact(paging: UserFocusAndFansPaging) {
    return await request.post(USER_CHATROOM_CONTACT, paging) as ResponseResult<UserMsg[]>;
  }
}

export {
  FileResponseEntity,
  FileDownloadResponseEntity,
  FileDataResponseEntity,
  DetailPageInfo,
  DetailResponseData,
  DetailPublish,
  ShareLinkEntity,
  FeedbackResponseEntity,
  FriendlyLinkEntity,
  QuestionResponse,
  QuestionInfo,
  AnswerResponse,
  AnswerReply,
  ReplyMode,
  DetailComments,
  Comment,
  UserMsgUpdateInfo,
  UserMsgUpdateResponse,
  UserOperationDetail,
  UserFocusOrFansPaging,
  UserFocusAndFansPaging,
  UserCentre7DaysStatics,
  UserMsg,
  LoginForm,
  RegisterForm,
  DetailInfo,
  KudosComment,
  DetailCommentInfo,
  QuestionPaging,
}
